<template>
  <div class="book-search-container">
    <div class="search-box">
      <input
        v-model="searchTerm"
        type="text"
        placeholder="输入关键词..."
        class="search-input"
        @keyup.enter="searchBooks"
      />
      <button @click="searchBooks" class="search-button">查询</button>
    </div>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="!loading && books.length > 0" class="book-results">
      <div v-for="book in books" :key="book.isbn" class="book-card">
        <!-- <img :src="getBookImage(book.isbn)" :alt="book.title" class="book-image" /> -->
        <h3>{{ book.title }}</h3>
        <p>作者：{{ book.author }}</p>
        <p>ISBN：{{ book.isbn }}</p>
        <p>剩余数量：{{ book.available_quantity }}</p>
        <p>状态：{{ book.status }}</p>
        <!-- <button @click="borrowBook(book.isbn)" class="borrow-button">借阅此书</button> -->
      </div>
    </div>

    <div v-if="!loading && books.length === 0 && searched" class="no-results">
      <p>未找到相关图书，请尝试其他关键词。</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'BookSearch',
  data() {
    return {
      searchTerm: '',
      books: [],
      loading: false,
      searched: false,
    };
  },
  methods: {
    async searchBooks() {
      if (!this.searchTerm.trim()) {
        return;
      }

      this.loading = true;
      this.searched = true;

      try {
        const response = await axios.get(
          `http://8.134.212.44:9999/index/main/select?keyword=${encodeURIComponent(this.searchTerm)}`
        );

        if (response.data.code === 0 && response.data.data) {
          this.books = response.data.data.map(book => ({
            title: book.Title,
            author: book.Author,
            isbn: book.Isbn,
            available_quantity: book.Available_quantity,
            status: book.Status
          }));
        } else {
          this.books = [];
          alert(`图书查询失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('图书查询失败:', error);
        this.books = [];
        this.handleNetworkError(error);
      } finally {
        this.loading = false;
      }
    },
    // getBookImage(isbn) {
    //   return `https://via.placeholder.com/150?text=ISBN:${isbn}`;
    // },
    handleNetworkError(error) {
      if (error.response) {
        console.error('后端错误:', error.response.data);
        alert(`图书查询失败，状态码: ${error.response.status}`);
      } else if (error.request) {
        console.error('网络请求失败:', error.request);
        alert('网络请求失败，请检查网络连接并重试');
      } else {
        console.error('请求错误:', error.message);
        alert('请求出错，请稍后重试');
      }
    },
    async borrowBook(isbn) {
      if (!isbn) return;

      const currentTime = new Date().toISOString();

      try {
        await axios.post(
          'http://8.134.212.44:9999/index/main/select',
          {
            isbn: isbn,
            borrowTime: currentTime,
          }
        );

        const bookIndex = this.books.findIndex(book => book.isbn === isbn);
        if (bookIndex !== -1) {
          this.books[bookIndex].available_quantity -= 1;

          if (this.books[bookIndex].available_quantity === 0) {
            this.books.splice(bookIndex, 1);
          }
        }

        alert(`成功借阅图书：${this.books[bookIndex].title}`);
      } catch (error) {
        console.error('借阅失败:', error);
        alert('借阅失败，请稍后重试');
      }
    },
  },
};
</script>

<style scoped>
.book-search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-box {
  display: flex;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

.search-button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.loading {
  text-align: center;
  padding: 20px;
}

.book-results {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.book-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.book-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.borrow-button {
  width: 100%;
  padding: 8px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

.no-results {
  text-align: center;
  padding: 20px;
  color: #666;
}
</style>